<?php

namespace app\api\controller;

use app\api\library\CommentException;
use think\Config;
use think\Exception;
use app\admin\model\cms\Plate;
use app\admin\model\cms\Platepost;
use app\common\model\User;
use think\Cookie;
use think\Validate;
use think\Db;

/**
 * 论坛
 */
class Bbs extends Base
{
    private $appid = 1;
    private $page =1;
    private $limit = 10;
    
    protected $noNeedLogin = ['GetPlateList',"GetPostList","GetPost"];
    //论坛系统
    /**
     * 获取版块列表
     */
    public function GetPlateList()
    {
        $field = 'id,platename,plateicon,iscomment,creattime,plateontent,status';     
        $forumList = Plate::where('status', 1)->field($field)->order('id', 'asc')->select();       
        return $this->success("获取成功", $forumList);
    }
    /**
     * 获取版块下的帖子列表
     */
    public function GetPostList()
    {
        $this->limit = $this->request->param('limit', 10, 'intval');  //每页显示条数
        $this->page = $this->request->param('page', 1, 'intval');   //当前页数
        $data = [
            'plateid' => $this->request->param('pid'),
        ];
        $rule = [
            'plateid' => 'require',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            $this->error($validate->getError());
        }
        $plate = Plate::where('id', $data['plateid'])->where('appid', $this->appid)->find();
        if (!$plate) {
            return $this->error('版块不存在');
        }
        $result = Db::table('fa_plate_post')
            ->alias('p')
            ->join('plate b', 'b.id = p.plateid')
            ->join('user u', 'u.id = p.user_id')
            ->where('p.plateid', $data['plateid'])
            ->where('p.is_audit', 1)
            ->field("p.id,p.postname,p.postcontent,p.username,p.plateid,p.replytime,u.nickname,b.platename,(select count(*) from fa_comment where aid = p.id and type='bbs') as commentnum")
//            ->field('(select count(*) from mr_likepost where postid = p.id) as likenum')
            ->field("(select count(*) from fa_plate_post where plateid = {$data['plateid']}) as postnum")
            ->order('p.top', 'asc')
            ->order('p.replytime', 'desc')
            ->limit($this->limit)
            ->page($this->page)
            ->select();
//    var_dump(Db::getLastSql());exit;
        return $this->success( "获取成功", $result);
    }
/**
     * 获取全部帖子
     */
    public function GetAllPostList()
    {
        $result =  Db::table('fa_plate_post')
            ->alias('p')
            ->join('plate b', 'b.id = p.plateid')
            ->join('user u', 'u.id = p.user_id')
            ->where('p.is_audit', 1)
            ->field('p.*,u.nickname,u.avatar,u.level,b.platename,(select count(*) from fa_comment where aid = p.id) as commentnum')
            ->field("(select count(*) from fa_user_like where object_id = p.id and table_name='bbs') as likenum")
            ->field("(select count(*) from fa_plate_post where plateid = p.plateid) as postnum")
            ->order('p.replytime', 'desc')
            ->limit($this->limit)
            ->page($this->page)
            ->select();
//        var_dump(Db::getLastSql());exit;
        return $this->success( "获取成功", $result);
    }
     /**
     * 获取帖子详情
     */
    public function GetPost()
    {
        $data = [
            'postid' => $this->request->param('postid'),
        ];
        $rule = [
            'postid' => 'require',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            $this->error( $validate->getError());
        }
        $post = PlatePost::where('id', $data['postid'])->find();
        if (!$post) {
            return $this->error( '帖子不存在');
        }
    
        $result =  Db::table('fa_plate_post')
            ->alias('p')
            ->join('plate b', 'b.id = p.plateid')
            ->join('user u', 'u.id = p.user_id')
            ->where('p.id', $data['postid'])
            ->field('p.*,u.nickname,u.avatar,u.level,b.platename,(select count(*) from fa_comment where aid = p.id) as commentnum')
            ->field("(select count(*) from fa_user_like where table_name='bbs' and object_id = p.id) as likenum")
            ->find();
        PlatePost::where('id', $data['postid'])->update(['view' => $post['view'] + 1]);
        return $this->success("获取成功", $result);
    }
/**
     * 新增帖子
     */
    public function AddPost()
    {
        $userId    = $this->auth->id;
        $data = [
            'plateid' => $this->request->param('plateid'),
            'postname' => $this->request->param('postname'),
            'postcontent' => $this->request->param('postcontent'),
        ];
        $rule = [
            'plateid' => 'require',
            'postname' => 'require',
            'postcontent' => 'require',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            $this->error( $validate->getError());
        }
        $user = User::where('id', $userId)->find();
        if (!$user) {
            return $this->error("用户不存在");
        }
        $plate = Plate::where('id', $data['plateid'])->find();
        if (!$plate) {
            return $this->error("版块不存在");
        }
//        echo $user->token.'=='. Cookie::get('usertoken');
        if ($user->token != Cookie::get('usertoken')) {
            return $this->error("用户token错误");
        }
        
        $upload = new Upload();
        $file = $upload->uploadDetail('file');
        $a = json_encode($file);
        $b = json_decode($a);
        $imgurl = '';
        foreach ($b as $v) {
            $imgurl .= $v->fullPath . ",";
        }
        if ($imgurl != '') {
            $imgurl = substr($imgurl, 0, -1);
        }
        $result = Db::table('fa_plate_post')
            ->insert([
                'plateid' => $data['plateid'],
                'postname' => $data['postname'],
                'postcontent' => $data['postcontent'],
//                'appid' => $this->appid,
                'username' => Cookie::get('username'),
                'user_id' => $userId,
                'creat_time' => date('Y-m-d H:i:s'),
                'replytime' => date('Y-m-d H:i:s'),
                'file' => $imgurl,
            ]);
//        $this->userLog($this->appid, Cookie::get('username'), '新增帖子', $data['postname']);
        return $this->success("发布成功");
    }
      /**
     * 编辑帖子
     */
    public function UpdatePost()
    {
        $userId    = $this->auth->id;
        $data = [
            'postid' => $this->request->param('postid'),
            'postname' => $this->request->param('postname'),
            'postcontent' => $this->request->param('postcontent'),
        ];
        $rule = [
            'postid' => 'require',
            'postname' => 'require',
            'postcontent' => 'require',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            $this->error($validate->getError());
        }
        $user = User::where('id', $userId)->find();
        if (!$user) {
            return $this->error("用户不存在");
        }
        //判断usertoken是否正确
        if ($user->token != Cookie::get('usertoken')) {
            return $this->error( "用户token错误");
        }
        //判断帖子是否存在
        $post = PlatePost::where('id', $data['postid'])->find();
        if (!$post) {
            return $this->error("帖子不存在");
        }
        //判断是否是自己的帖子
        if ($post->user_id != $userId) {
            return $this->error("不是自己的帖子");
        }

        $upload = new Upload();
        $file = $upload->uploadDetail('file');
        $a = json_encode($file);
        $b = json_decode($a);
        $imgurl = '';
        foreach ($b as $v) {
            $imgurl .= $v->fullPath . ",";
        }
        if ($imgurl != '') {
            $imgurl = substr($imgurl, -1);
        }
        $result =  Db::table('fa_plate_post')
            ->where('id', $data['postid'])
            ->update([
                'postname' => $data['postname'],
                'postcontent' => $data['postcontent'],
                'file' => $imgurl,
            ]);
//        $this->userLog($this->appid, Cookie::get('username'), "修改了帖子:" . $data['postname']);
        return $this->success("编辑成功");
    }

    /**
     * 删除帖子
     */
    public function DeletePost()
    {
        $userId    = $this->auth->id;
        $data = [
            'postid' => $this->request->param('postid'),
        ];
        $rule = [
            'postid' => 'require',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            $this->error( $validate->getError());
        }
        $user = User::where('id', $userId)->where('appid', $this->appid)->find();
        if (!$user) {
            return $this->error( "用户不存在");
        }
        //判断usertoken是否正确
        if ($user->user_token != Cookie::get('usertoken')) {
            return $this->error( "用户token错误");
        }
        //判断帖子是否存在
        $post = PlatePost::where('id', $data['postid'])->where('appid', $this->appid)->find();
        if (!$post) {
            return $this->error( "帖子不存在");
        }
        //判断是否是自己的帖子
        if ($post->user_id != $userId) {
            return $this->error( "不是自己的帖子");
        }
      
        $result =  Db::table('fa_plate_post')
            ->where('id', $data['postid'])
            ->delete();
//        $this->userLog($this->appid, Cookie::get('username'), "修改了帖子:" . $post['postname']);
        return $this->success("删除成功");
    }
    /**
     * 获取用户发表的帖子
     */
    public function GetUserPostList()
    {
        $userId    = $this->auth->id;
//        $user = User::where('id', $userId)->where('appid', $this->appid)->find();
        if (!$userId) {
            return $this->error( "用户不存在");
        }
       
        $result = Db::table('fa_plate_post')
            ->alias('p')
            ->join('plate b', 'b.id = p.plateid')
            ->join('user u', 'u.id = p.user_id')
            ->where('p.user_id', $userId)
            ->field('p.*,u.nickname,u.avatar,b.platename,(select count(*) from fa_comment where aid = p.id) as commentnum')
            ->field("(select count(*) from fa_user_like where object_id = p.id and table_name ='bbs') as likenum")
            ->order('p.replytime', 'desc')
            ->limit($this->limit)
            ->page($this->page)
            ->select();
        return $this->success("获取成功", $result);
    }
  /**
     * 搜索帖子
     */
    public function SearchPost()
    {
        $data = [
            'keyword' => $this->request->param('keyword'),
        ];
        $rule = [
            'keyword' => 'require',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            $this->error( $validate->getError());
        }
     
        $result = Db::table('fa_plate_post')
            ->alias('p')
            ->join('plate b', 'b.id = p.plateid')
            ->join('user u', 'u.id = p.user_id')
            ->where('p.postname', 'like', '%' . $data['keyword'] . '%')
            ->whereOr('p.postcontent', 'like', '%' . $data['keyword'] . '%')
            ->field('p.*,u.nickname,u.avatar,u.level,b.platename,(select count(*) from fa_comment where aid = p.id) as commentnum')
            ->field("(select count(*) from fa_user_like where object_id = p.id and table_name='bbs') as likenum")
            ->order('p.replytime', 'desc')
            ->limit($this->limit)
            ->page($this->page)
            ->select();
        return $this->success("获取成功", $result);
    }
}
?>